<template>
	<view class="my-select">
		<u-input v-model="sValue" type="select" v-bind='attrs' :class="showClearable?'isClearable':''"
			:clearable="props.clearable" @click="onShowSelect()">
			<template #right-icon>
				<view class="right-icon-box">
					<text class="clearable-btn" v-if='showClearable' @tap.stop="clearableFu">×</text>
					<text class="drop-down">
						<!-- > -->
					</text>
				</view>
			</template>
		</u-input>

		<u-popup v-model="show" mode="center" width="90%" border-radius="14" :closeable='true'>
			<view>
				<view class="p-14">
					<group-title>
						<template #icon>
							<view class="main-color">
								<u-icon name="title-icon" custom-prefix="custom-icon" />
							</view>
						</template>
						选择门店
					</group-title>
				</view>
				<view>
					<view class="p-x-16 m-b-16">
						<u-search placeholder="搜索关键词" v-model="queryForm.storeNameLeftLike" :show-action="false"
							shape='square' @input='onSearch'></u-search>
					</view>
					<scroll-view class="popup-content" scroll-y :scroll-with-animation="true" :scroll-top="scrollToTop"
						@scrolltolower="handleScrollToLower">
						<!-- 选项列表 -->
						<template>
							<view class="" v-for="(item,index) in listData" :item='item.id' @tap="selectOption(item)">
								<view class="mch-card m-x-16 m-b-8 p-8" :class="isSelected(item)?'hit':'unhit'">
									<view class="flex flex-row justify-between">
										<group-title>
											<template #icon>
												<view class="p-r-8 title-icon">
													<view class="mch-icon flex justify-content items-center">
														✔
													</view>
												</view>
											</template>
											{{item.storeName}}
										</group-title>
										<view :class="item.status!=0?'u-type-success':''">
											<!-- {{selectDictLabel(ZZB_MCH_NO_STATUS,item.status)}} -->
											{{item.status=='0'?'禁用':'启用'}}
										</view>
									</view>
									<view class="flex flex-row justify-between line-h-16 p-b-4">
										<view class="list-title">
											联系人
										</view>
										<view class="list-value">
											{{item.name}}
										</view>
									</view>
									<view class="flex flex-row justify-between line-h-16 p-b-4">
										<view class="list-title">
											门店类型
										</view>
										<view class="list-value">
											{{selectDictLabel(ZZB_STORE_TYPE,item.type)}}
										</view>
									</view>
								</view>
							</view>
						</template>
						<template>
							<view>
								<!-- 底部加载状态 -->
								<view v-if="loading" class="loading">
									<text class="loading-dot">●</text>
									<text class="loading-dot">●</text>
									<text class="loading-dot">●</text>
								</view>
								<!-- 无更多数据 -->
								<view v-if="!hasMore && !loading" class="no-more">
									没有更多了
								</view>
							</view>
						</template>
					</scroll-view>
				</view>
				<view class="p-16 flex flex-row justify-between items-center">
					<view class="grow p-l-8">
						<u-button type="primary" @click="okMch">确认</u-button>
					</view>
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script setup>
	import {
		ref,
		watch,
		computed,
		useAttrs,
		onMounted,
		getCurrentInstance
	} from 'vue'
	import {
		onLoad,
		onReady,
		onShow
	} from '@dcloudio/uni-app'
	import {
		ZZB_STORE_TYPE
	} from '@/common/dict.js'
	import {
		selectDictLabel
	} from '@/common/common.js'
	import {
		storeApi
	} from '@/common/api/store/index.js'
	import {
		handleTree,
		strToArr,
		debounce
	} from '@/common/common.js'

	import {
		isEmpty
	} from '@/common/system.js'
	const {
		proxy
	} = getCurrentInstance()
	const attrs = useAttrs()
	const maiColor = computed(() => {
		return proxy.$System.maiColor.value
	})

	const props = defineProps({
		// 选中值
		modelValue: {
			type: [String, Number, Object, Array],
			default: null
		},
		// 是否可清除
		clearable: {
			type: Boolean,
			default: false
		},
		// 是否返回多个值
		multiple: {
			type: Boolean,
			default: false,
		},
		// 初始化参数，为回显时使用
		initParams: {
			type: Object,
			default: () => ({}),
		},
		queryParams: {
			type: Object,
			default: () => ({}),
		},
		valueKey: {
			type: String,
			default: 'id'
		},
		labelKey: {
			type: String,
			default: 'storeName'
		}

	})

	const emit = defineEmits(['update:modelValue', 'change'])

	const mValue = computed(() => {
		return strToArr(props.modelValue)
	})
	const selected = computed({
		get: () => {
			if (mValue.length == 0) return
			let sVal = selectedItem.value.filter(item =>
				mValue.value.some(e => e == item[props.valueKey])
			)
			if (sVal.length == 0) {
				return props.modelValue
			} else {
				let rVal = sVal.map(item => item[props.labelKey]).toString()
				return rVal
			}
		},
		set: (val) => {
			emit('update:modelValue', val)
			return
		}
	})
	const sValue = computed(() => {
		return selected.value ?? ''
	})

	const showClearable = computed(() => {
		return props.clearable && !isEmpty(props.modelValue)
	})

	const show = ref(false)
	const onShowSelect = () => {
		show.value = true
		// console.log('show.value=>>>', show.value);
	}

	// 列表数据
	const listData = ref([])
	// 清除数据
	const clearableFu = () => {
		selectedItem.value = []
		emit('update:modelValue', undefined)
	}
	// 选中项
	const selectedItem = ref([])

	// 判断是否选中
	const isSelected = (item) => {
		if (props.multiple) {
			// 多选模式
			return selectedItem.value.some(e => e[props.valueKey] == item[props.valueKey])
		} else {
			// 单选模式
			if (selectedItem.value.length === 0) return false
			return selectedItem.value[0][props.valueKey] == item[props.valueKey]
		}
	}

	// 选择选项
	const selectOption = (item) => {
		if (props.multiple) {
			// 根据id判断当前点击的是否被选中
			const isS = selectedItem.value.findIndex(obj => obj[props.valueKey] == item[props.valueKey])
			if (isS >= 0) {
				selectedItem.value.splice(isS, 1)
			} else {
				selectedItem.value.push(item)
			}
			emit('update:modelValue', selectedItem.value.map(e => e[props.valueKey]))
		} else {
			emit('update:modelValue', item[props.valueKey])
			selectedItem.value = [item]
		}
		emit('change', selectedItem.value)
	}

	// 是否滚动到顶部
	const scrollToTop = ref(0)
	const loading = ref(false)
	// 是否还有更多数据
	const hasMore = computed(() => {
		// 最后一页返回的数据条数小于pageSize，说明没有更多数据了
		console.log('111111111', listData.value);
		const lastPageSize = listData.value?.length % queryForm.value.pageSize
		return !loading.value && (!lastPageSize || lastPageSize === queryForm.value.pageSize)
	})

	// 默认参数
	const initForm = {
		storeNameLeftLike: undefined,
		pageNo: 1,
		pageSize: 10,
	}
	const queryForm = ref({
		...initForm
	})
	// 过去列表数据
	const getData = async (params) => {
		let res = await storeApi.page(params)
		if (res.code != 200) return
		return res.data
	}

	const ininList = async () => {
		let params = {
			...queryForm.value,
			...props.queryParams
		}
		let data = await getData(params)
		console.log('res===>', data);
		listData.value = data
	}

	const ininLable = async () => {
		let params = {
			...queryForm.value,
			...props.queryParams,
			...props.initParams,
		}
		let data = await getData(params)
		if (!isEmpty(data)) {
			selectedItem.value = data
		}
	}

	// 搜索处理
	const onSearch = debounce(async (val) => {
		queryForm.value.storeNameLeftLike = val
		// 远程搜索
		queryForm.value.pageNo = 1
		listData.value = []
		loading.value = true
		let params = {
			...queryForm.value,
			...props.queryParams
		}
		let data = await getData(params)

		listData.value = data
		scrollToTop.value = 0
		loading.value = false
	}, 500)

	// 滚动到底部
	const handleScrollToLower = debounce(async () => {
		if (loading.value || !hasMore.value) return
		loading.value = true
		queryForm.value.pageNo++
		let params = {
			...queryForm.value,
			...props.queryParams
		}
		let data = await getData(params)
		// 追加数据
		listData.value = [...listData.value, ...data]

		loading.value = false
		// 如果返回的数据条数小于pageSize，说明没有更多数据了
		if (data.length < props.pageSize) {
			hasMore.value = false
		}
	}, 500)

	// 确认
	const okMch = () => {
		show.value = false
	}

	// watch(() => listData.value, () => {
	// 	// 在当前listData中查找
	// 	const found = listData.value.filter(item =>
	// 		mValue.value.some(e => e == item[props.valueKey])
	// 	)
	// 	if (!isEmpty(found)) {
	// 		selectedItem.value = found
	// 		return
	// 	} else if (mValue.value.length > 0) {
	// 		selectedItem.value = isEmpty(selectedItem.value) ? createDefaultSelectedItem(mValue.value) :
	// 			selectedItem
	// 			.value
	// 	}
	// }, {
	// 	deep: true
	// })

	watch(() => props.queryParams, () => {
		ininList()
	}, {
		deep: true,
		immediate: true
	})

	watch([() => props.initParams], () => {
		if (!isEmpty(props.initParams) && !isEmpty(props.modelValue) && !show.value) {
			ininLable()
		}
	}, {
		deep: true
	})

	onLoad((opt) => {})
	onShow(() => {})

	defineExpose({
		onShowSelect,
		selectedItem,
		sValue,
		clearableFu
	})
</script>

<style lang='scss' scoped>
	.my-select {
		width: 100%;
		position: relative;

		.isClearable {
			:deep([type="select"]) {
				padding-right: 0.5rem;
			}
		}
	}

	/* 	:deep(.my-select .isClearable .u-input__input.u-input__select) {
		padding-right: 1rem;
	} */
	.right-icon-box {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.drop-down {
		display: inline-block;
		color: #c0c4cc;
		transform: rotate(45deg);
		-ms-transform: rotate(45deg);
		/* IE 9 */
		-webkit-transform: rotate(45deg);
		/* Safari and Chrome */

		:after {
			display: block;
			content: '';
			width: 18rpx;
			height: 18rpx;
			border-top: #c0c4cc 4rpx solid;
			border-right: #c0c4cc 4rpx solid;
		}
	}

	.clearable-btn {
		background-color: #c0c4cc;
		color: #fff;
		border-radius: 500px;
		display: flex;
		justify-content: center;
		/* align-items: center; */
		font-size: 0.85rem;
		width: 1.2rem;
		height: 1.2rem;
		line-height: 1.2rem;
		margin-right: 8rpx;
	}

	.loading {
		text-align: center;
		padding: 20rpx;
		color: #999;
		font-size: 24rpx;
		display: flex;
		justify-content: center;
		gap: 8rpx;
		background: #fff;
	}

	.loading-dot {
		animation: loading 1s infinite;
	}

	.loading-dot:nth-child(2) {
		animation-delay: 0.2s;
	}

	.loading-dot:nth-child(3) {
		animation-delay: 0.4s;
	}

	@keyframes loading {

		0%,
		100% {
			opacity: 0.3;
		}

		50% {
			opacity: 1;
		}
	}

	.no-more {
		text-align: center;
		padding: 20rpx;
		color: #999;
		font-size: 24rpx;
		background: #fff;
	}

	.popup-content {
		height: 60vh;

		.mch-card {
			border-radius: 16rpx;
			background-color: rgba(246, 247, 248, 1);
		}

		.mch-icon {
			width: 32rpx;
			height: 32rpx;
			color: #fff;
			border-radius: 50px;
			font-size: 0.6em;
		}

		.hit {
			border: var(--maiColor) solid 1rpx;

			.title-icon {
				.mch-icon {
					border: var(--maiColor) solid 1rpx;
					background-color: var(--maiColor);
				}
			}
		}

		.unhit {
			border: rgba(246, 247, 248, 1) solid 1rpx;

			.title-icon {
				.mch-icon {
					border: rgba(231, 230, 228, 1) solid 1rpx;
					background-color: #fff;
				}
			}
		}
	}
</style>